package com.hicorp.segment.service.impl;

import com.hicorp.segment.mapper.ApprovalReceiptRecordMapper;
import com.hicorp.segment.mapper.OrderReceiptsSubMaterialMapper;
import com.hicorp.segment.mapper.ReceiptsMapper;
import com.hicorp.segment.mapper.ReceiptsSubMapper;
import com.hicorp.segment.pojo.po.*;
import com.hicorp.segment.service.ReceiptsService;
import com.hicorp.segment.utils.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author:
 * @Date: Created in 17:52 2021/5/31
 * @Description:
 * @ChineseDescription:
 * @Modified_By:
 */
@Service("receiptsService")
@Slf4j
public class ReceiptsServiceImpl implements ReceiptsService {
    @Resource
    private ReceiptsMapper receiptsMapper;
    @Resource
    private ApprovalReceiptRecordMapper approvalReceiptRecordMapper;
    @Resource
    private ReceiptsSubMapper receiptsSubMapper;
    @Resource
    private OrderReceiptsSubMaterialMapper orderReceiptsSubMaterialMapper;


    @Override
    public ResultBean<List<Receipts>> queryInfo(String tableName) {
        try {
            List<Receipts> receiptsList = receiptsMapper.queryInfo(tableName);
            return new ResultBean<>(receiptsList);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)   //回滚
    public ResultBean<Integer> insert(Receipts receipts) {
        try {
            receipts.setTableNameSub(receipts.getTableName() + "_sub");
            Integer integer = receiptsMapper.insertReceipts(receipts);
            //for循环，每个receiptsSub都加上表名
            if (receipts.getReceiptsSub() != null) {
                receipts.getReceiptsSub().forEach(receiptsSub -> {
                            receiptsSub.setTableName(receipts.getTableName() + "_sub");
                            receiptsSubMapper.insertReceiptsSub(receiptsSub);
                        }
                );
            }
            return new ResultBean<>(integer);
        } catch (Exception e) {
            log.error(e.getMessage());
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)   //回滚
    public ResultBean<Integer> update(Receipts receipts) {
        try {
            Integer integer = receiptsMapper.updateReceipts(receipts);
            String no = receiptsMapper.selectNoById(receipts.getTableName(), receipts.getId());
            //通过no删掉以前的sub表中的内容
            receiptsSubMapper.batchDeleteRecord(no, receipts.getTableName() + "_sub");
            receipts.getReceiptsSub().forEach(receiptsSub -> {
                        receiptsSub.setTableName(receipts.getTableName() + "_sub");
                        receiptsSubMapper.insertReceiptsSub(receiptsSub);
                    }
            );
            return new ResultBean<>(integer);
        } catch (Exception e) {
            log.error(e.getMessage());
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }

    //批量删除
    @Override
    @Transactional(rollbackFor = Exception.class)   //回滚
    public ResultBean<Integer> batchDeleteRecord(String tableName, List<Long> ids) {
        try {
            //for循环，每个receiptsSub都加上表名
            ids.forEach(id -> {
                String no = receiptsMapper.selectNoById(tableName, id);
                receiptsSubMapper.batchDeleteRecord(no, tableName + "_sub");
            });
            Integer integer = receiptsMapper.batchDeleteRecord(ids, tableName);
            return new ResultBean<>(integer);
        } catch (Exception e) {
            log.error(e.getMessage());
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }

    //批量作废
    @Override
    @Transactional(rollbackFor = Exception.class)   //回滚
    public ResultBean<Integer> batchInvalidRecord(String tableName, List<Long> ids) {
        try {
            Integer integer = receiptsMapper.batchInvalidRecord(ids, tableName);
            return new ResultBean<>(integer, 201, "");
        } catch (Exception e) {
            log.error(e.getMessage());
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }

    //单据主表搜索，未实现
    @Override
    public Object selectRecords(String tableName, String fieldName, String fieldValue) {
        return null;
    }

    //生成单据内部编号
    @Override
    public ResultBean<String> generateReceiptsNo(String tableName, String preNo) {
        try {
            String returnNO = receiptsMapper.generateReceiptsNo(tableName, preNo + "%");
            if (returnNO == null) {
                returnNO = preNo + "0001";
            } else {
                String str1 = "000" + (Integer.parseInt(returnNO.substring(12)) + 1);
                returnNO = preNo + str1.substring(str1.length() - 4);
            }
            return new ResultBean<>(returnNO);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResultBean<>(400, "创建内部编号失败!");
        }
    }


    // 查询，通过表名和内部编码来获取主子表数据
    @Override
    public ResultBean<Receipts> selectByTableNameAndNo(String tableName, String no) {
        try {
            Receipts receipts = receiptsMapper.selectByTableNameAndNo(tableName, no);
            return new ResultBean<>(receipts);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    // 远程搜索数据获取，通过表名
    @Override
    public ResultBean<List<MaterialConcrete>> selectAutocompleteInput(String tableName) {
        try {
            List<MaterialConcrete> material = receiptsMapper.selectAutocompleteInput();
            System.out.println(material);
            return new ResultBean<>(material);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    // 通过no和itemNo来查找订单单据物料BOM表中的数据
    @Override
    public ResultBean<List<OrderReceiptSubMaterial>> selectOrderReceiptsSubMaterial(String tableName, String no, String itemNo) {
        try {
            List<OrderReceiptSubMaterial> orderReceiptsSubMaterialList = receiptsMapper.selectOrderReceiptsSubMaterial(no, itemNo);
            return new ResultBean<>(orderReceiptsSubMaterialList);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    // 通过no和itemNo来查找订单单据物料BOM表中的数据
    @Override
    public ResultBean<Integer> submitOrderMaterial(String tableName, ArrayList<OrderReceiptSubMaterial> orderReceiptSubMaterialList, String no, String itemNo) {
        try {
            if (orderReceiptSubMaterialList.isEmpty()) {
                return new ResultBean<>(1);
            } else {
                //通过no和itemNo删掉以前的subMaterial表中的内容
                receiptsSubMapper.batchDeleteRecordMaterial(no, itemNo, "order_receipt_sub_material");
                //新增
                orderReceiptSubMaterialList.forEach(orderReceiptSubMaterial -> orderReceiptsSubMaterialMapper.insert(orderReceiptSubMaterial));
            }
            return new ResultBean<>(1);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    //组合搜索
    @Override
    public ResultBean<List<Receipts>> searchRecord(String tableName, Receipts receipts) {
        try {
            receipts.setNo("%" + (receipts.getNo() == null ? "" : receipts.getNo()) + "%");
            receipts.setName("%" + (receipts.getName() == null ? "" : receipts.getName()) + "%");
            receipts.setNoHand("%" + (receipts.getNoHand() == null ? "" : receipts.getNoHand()) + "%");
            receipts.setRemark("%" + (receipts.getRemark() == null ? "" : receipts.getRemark()) + "%");
            receipts.setReceiptsType("%" + (receipts.getReceiptsType() == null ? "" : receipts.getReceiptsType()) + "%");
            receipts.setInvalid("%" + (receipts.getInvalid() == null ? "" : receipts.getInvalid()) + "%");
            receipts.setCreateUser("%" + (receipts.getCreateUser() == null ? "" : receipts.getCreateUser()) + "%");
            receipts.setModifiedUser("%" + (receipts.getModifiedUser() == null ? "" : receipts.getModifiedUser()) + "%");
            receipts.setCreateGmtStart(receipts.getCreateGmtStart() == null ? new Date(1) : receipts.getCreateGmtStart());
            receipts.setCreateGmtEnd(receipts.getCreateGmtEnd() == null ? new Date() : receipts.getCreateGmtEnd());
            receipts.setModifiedGmtStart(receipts.getModifiedGmtStart() == null ? new Date(1) : receipts.getModifiedGmtStart());
            receipts.setModifiedGmtEnd(receipts.getModifiedGmtEnd() == null ? new Date() : receipts.getModifiedGmtEnd());
            receipts.setTableNameSub(receipts.getTableName() + "_sub");
            List<Receipts> receiptsList = receiptsMapper.searchRecord(receipts);
            return new ResultBean<>(receiptsList, 201, "成功");
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    // 提交审批
    @Override
    @Transactional(rollbackFor = Exception.class)   //回滚
    public ResultBean<Integer> submitApproveRecord(String tableName, String approveStatus, Receipts receipts) {
        String no = receipts.getNo();
        try {
            Integer integer = receiptsMapper.approveReceipts(tableName, approveStatus, no);
            return new ResultBean<>(integer, 201, "");
        } catch (Exception e) {
            log.error(e.getMessage());
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }

    // 审批
    @Override
    @Transactional(rollbackFor = Exception.class)   //回滚
    public ResultBean<Integer> approveRecord(String tableName, String approveStatus, String remark, String user, String role, Receipts receipts) {
        String no = receipts.getNo();
        try {
            ApprovalReceiptRecord approvalReceiptRecord = new ApprovalReceiptRecord();
            approvalReceiptRecord.setApprovalResult(approveStatus);
            approvalReceiptRecord.setReceiptNo(no);
            approvalReceiptRecord.setReceiptName("订单");
            approvalReceiptRecord.setApprovalRole(role);
            approvalReceiptRecord.setApprovalPeople(user);
            approvalReceiptRecord.setApprovalTime(new Date());
            approvalReceiptRecord.setRemark(remark);
            approvalReceiptRecordMapper.insert(approvalReceiptRecord);
            Integer integer = receiptsMapper.approveReceipts(tableName, approveStatus, no);
            return new ResultBean<>(integer, 201, "");
        } catch (Exception e) {
            log.error(e.getMessage());
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }
}
